﻿using Furion.CMS.Application.Dto;
using Furion.CMS.Core.Base;
using Furion.CMS.Domain;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace Furion.CMS.Application
{
    /// <summary>
    /// 日志应用服务
    /// </summary>
    public class LogsAppService : BaseApplication
    {
        private readonly IRepository<AuditLog> _auditLogRepository;

        public LogsAppService(IRepository<AuditLog> auditLogRepository)
        {
            _auditLogRepository = auditLogRepository;
        }

        /// <summary>
        /// 获取操作日志
        /// </summary>
        /// <param name="index"></param>
        /// <param name="limit"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="operateRange">操作范围</param>
        /// <returns></returns>
        [HttpPost]
        [ApiDescriptionSettings(Name = "operate")]
        public PagingList<OperateLogDto> GetOperateLogs([ApiSeat(ApiSeats.ActionStart)] int index, [ApiSeat(ApiSeats.ActionStart)] int limit,
            [FromQuery] DateTimeOffset? startTime, [FromQuery] DateTimeOffset? endTime, [FromBody] string[] operateRange)
        {
            var query = _auditLogRepository.AsQueryable(false)
                .Where(startTime.HasValue, x => x.CreatedTime >= startTime.Value.Date)
                .Where(endTime.HasValue, x => x.CreatedTime < endTime.Value.AddDays(1).Date)
                .Where(operateRange.Any(), x => operateRange.Contains(x.Operate))
                .Include(i => i.User)
                .OrderByDescending(o => o.CreatedTime);

            // 排序之后再进行分页处理
            var pageResult = new PagingList<OperateLogDto> { Current = index, PageSize = limit, Total = query.Count() };
            pageResult.List = query.AsPagedQuery(index, limit).Adapt<List<OperateLogDto>>();
            return pageResult;
        }
    }
}
